//
//  XMPPvCardTemp+AddressingTypes.m
//  Gabber
//
//  Created by 陆惠国 on 11-11-3.
//  Copyright (c) 2011年 恒生聚源. All rights reserved.
//

#import "XMPPvCardTemp+AddressingTypes.h"


@implementation XMPPvCardTemp (AddressingTypes)

- (NSArray *)addresses 
{ 
    NSArray *result = nil;
	NSArray *elems = [self elementsForName:@"ADR"];
    if ([elems count] > 0){
        NSMutableArray *arr = [[NSMutableArray alloc] initWithCapacity:[elems count]];
        for (NSXMLElement *elem in elems) {
            [arr addObject:[XMPPvCardTempAdr vCardAdrFromElement:elem]];
        }  
        result = [NSArray arrayWithArray:arr];
		[arr release];
	}
	return result;
}

//- (void)addAddress:(XMPPvCardTempAdr *)adr
//{
//    [self addChild:adr];
//}
//
//- (void)removeAddress:(XMPPvCardTempAdr *)adr
//{
//    [self removeChildAtIndex:[[self children] indexOfObject:adr]];
//}
//
//- (void)setAddresses:(NSArray *)adrs
//{
//    [self clearAddresses];
//    for (XMPPvCardTempAdr *adr in adrs) {
//        [self addAddress:adr];
//    }    
//}

- (void)clearAddresses
{
    NSArray *elems = [self elementsForName:@"ADR"];
    
    for (NSXMLElement *elem in elems) {
        [self removeChildAtIndex:[[self children] indexOfObject:elem]];
    }
}


- (NSArray *)labels
{
    NSArray *result = nil;
	NSArray *elems = [self elementsForName:@"LABEL"];
    if ([elems count] > 0){
        NSMutableArray *arr = [[NSMutableArray alloc] initWithCapacity:[elems count]];
        for (NSXMLElement *elem in elems) {
            [arr addObject:[XMPPvCardTempLabel vCardLabelFromElement:elem]];
        }  
        result = [NSArray arrayWithArray:arr];
		[arr release];
	}
	return result;
}

//- (void)addLabel:(XMPPvCardTempLabel *)label 
//{
//    [self addChild:label];
//}
//
//- (void)removeLabel:(XMPPvCardTempLabel *)label
//{
//    [self removeChildAtIndex:[[self children] indexOfObject:label]];
//}
//
//- (void)setLabels:(NSArray *)labels
//{
//    [self clearLabels];
//    for (XMPPvCardTempLabel *label in labels) {
//        [self addLabel:label];
//    }    
//}

- (void)clearLabels
{
    NSArray *elems = [self elementsForName:@"LABEL"];
    
    for (NSXMLElement *elem in elems) {
        [self removeChildAtIndex:[[self children] indexOfObject:elem]];
    }
}


- (NSArray *)telecomsAddresses 
{ 
	NSArray *result = nil;
	NSArray *elems = [self elementsForName:@"TEL"];
    if ([elems count] > 0){
        NSMutableArray *arr = [[NSMutableArray alloc] initWithCapacity:[elems count]];
        for (NSXMLElement *elem in elems) {
            [arr addObject:[XMPPvCardTempTel vCardTelFromElement:elem]];
        }  
        result = [NSArray arrayWithArray:arr];
		[arr release];
	}
	return result;
}

//- (void)addTelecomsAddress:(XMPPvCardTempTel *)tel
//{
//    [self addChild:tel];
//}
//
//- (void)removeTelecomsAddress:(XMPPvCardTempTel *)tel
//{
//    [self removeChildAtIndex:[[self children] indexOfObject:tel]];
//}
//
//- (void)setTelecomsAddresses:(NSArray *)tels
//{
//    [self clearTelecomsAddresses];
//    for (XMPPvCardTempTel *tel in tels) {
//        [self addTelecomsAddress:tel];
//    }      
//}

- (void)clearTelecomsAddresses
{ 
    NSArray *elems = [self elementsForName:@"TEL"];
    
    for (NSXMLElement *elem in elems) {
        [self removeChildAtIndex:[[self children] indexOfObject:elem]];
    }
}


- (NSArray *)emailAddresses 
{
	NSArray *result = nil;
	NSArray *elems = [self elementsForName:@"EMAIL"];
    if ([elems count] > 0){
        NSMutableArray *arr = [[NSMutableArray alloc] initWithCapacity:[elems count]];
        for (NSXMLElement *elem in elems) {
            [arr addObject:[XMPPvCardTempEmail vCardEmailFromElement:elem]];
        }  
        result = [NSArray arrayWithArray:arr];
		[arr release];
	}
	return result;
}

//- (void)addEmailAddress:(XMPPvCardTempEmail *)email 
//{
//    [self addChild:email];
//}
//
//- (void)removeEmailAddress:(XMPPvCardTempEmail *)email 
//{ 
//    [self removeChildAtIndex:[[self children] indexOfObject:email]];
//}
//
//- (void)setEmailAddresses:(NSArray *)emails 
//{ 
//    [self clearEmailAddresses];
//    for (XMPPvCardTempEmail *email in emails) {
//        [self addEmailAddress:email];
//    }  
//}

- (void)clearEmailAddresses
{
    NSArray *elems = [self elementsForName:@"EMAIL"];
    
    for (NSXMLElement *elem in elems) {
        [self removeChildAtIndex:[[self children] indexOfObject:elem]];
    }
}

- (ABRecordRef) createPerson;
{
    ABRecordRef person = ABPersonCreate();
    CFErrorRef anError = NULL;
    
    
    if (self.photo){
        NSData *dataRef = self.photo; 
        CFDataRef dr = CFDataCreate(NULL, [dataRef bytes], [dataRef length]);
        
        ABPersonSetImageData(person, dr, &anError);
        CFRelease(dr);
    }
    
    if (TTIsStringWithAnyText(self.givenName)) {
        ABRecordSetValue(person, kABPersonFirstNameProperty, self.givenName, &anError);
    }
    if (TTIsStringWithAnyText(self.familyName)) {
        ABRecordSetValue(person, kABPersonLastNameProperty, self.familyName, &anError);
    }
    if (TTIsStringWithAnyText(self.middleName)) {
        ABRecordSetValue(person, kABPersonMiddleNameProperty, self.middleName, &anError);
    }
    if (TTIsStringWithAnyText(self.prefix)) {
        ABRecordSetValue(person, kABPersonPrefixProperty, self.prefix, &anError);    
    }
    if (TTIsStringWithAnyText(self.suffix)) {
        ABRecordSetValue(person, kABPersonSuffixProperty, self.suffix, &anError);  
    }
    if (TTIsStringWithAnyText(self.nickname)) {
        ABRecordSetValue(person, kABPersonNicknameProperty, self.nickname, &anError);  
    }
    if (TTIsStringWithAnyText(self.orgName)) {        
        ABRecordSetValue(person, kABPersonOrganizationProperty, self.orgName, &anError);      
    }
    if (TTIsStringWithAnyText(self.title)) {
        ABRecordSetValue(person, kABPersonJobTitleProperty, self.title, &anError);  
    }
    if (self.bday != nil) {
        ABRecordSetValue(person, kABPersonBirthdayProperty, self.bday, &anError);   
    }
    if (TTIsStringWithAnyText(self.note)) {
        
        ABRecordSetValue(person, kABPersonNoteProperty, self.note, &anError);  
    }
    
    ABMultiValueRef phone = ABMultiValueCreateMutable(kABMultiStringPropertyType);
    
    for(XMPPvCardTempTel* tel in self.telecomsAddresses)
    {
        if (TTIsStringWithAnyText(tel.number)) {
            if(tel.isCell){
                ABMultiValueAddValueAndLabel(phone, tel.number, kABPersonPhoneMobileLabel, NULL);
            }else if(tel.isPreferred){
                ABMultiValueAddValueAndLabel(phone, tel.number, kABPersonPhoneMainLabel, NULL);
            }else if(tel.isFax) {
                if(tel.isHome){
                    ABMultiValueAddValueAndLabel(phone, tel.number, kABPersonPhoneHomeFAXLabel, NULL);
                } else if(tel.isWork) {
                    ABMultiValueAddValueAndLabel(phone, tel.number, kABPersonPhoneWorkFAXLabel, NULL);
                } else {
                    ABMultiValueAddValueAndLabel(phone, tel.number, kABPersonPhoneOtherFAXLabel, NULL);
                }
            } else if(tel.isPager) {
                ABMultiValueAddValueAndLabel(phone, tel.number, kABPersonPhonePagerLabel, NULL);
            } else if(tel.isHome) {
                ABMultiValueAddValueAndLabel(phone, tel.number, kABHomeLabel, NULL);
            } else if(tel.isWork) {
                ABMultiValueAddValueAndLabel(phone, tel.number, kABWorkLabel, NULL);
            } else {
                ABMultiValueAddValueAndLabel(phone, tel.number, kABOtherLabel, NULL);
            }
        }
        
        
    }
    ABRecordSetValue(person, kABPersonPhoneProperty, phone, &anError);
    CFRelease(phone);
    
    
    ABMultiValueRef email = ABMultiValueCreateMutable(kABMultiStringPropertyType);
    
    for(XMPPvCardTempEmail* eml in self.emailAddresses)
    {
        if (TTIsStringWithAnyText(eml.userid)) {
            if(eml.isHome){
                ABMultiValueAddValueAndLabel(email, eml.userid, kABHomeLabel, NULL);
            }else if(eml.isWork){
                
                ABMultiValueAddValueAndLabel(email, eml.userid, kABWorkLabel, NULL);
            }else 
            {
                ABMultiValueAddValueAndLabel(email, eml.userid, kABOtherLabel, NULL);
            }
        }
        
        
    }
    ABRecordSetValue(person, kABPersonEmailProperty, email, &anError);
    CFRelease(email);
    
    
    ABMultiValueRef address = ABMultiValueCreateMutable(kABMultiDictionaryPropertyType);
    
    for(XMPPvCardTempAdr* adr in self.addresses)
    {
        NSMutableDictionary *addressDictionary = [[NSMutableDictionary alloc] init];
        if (TTIsStringWithAnyText(adr.street)) {
            [addressDictionary setObject:adr.street forKey:(NSString *) kABPersonAddressStreetKey];
        }
        if (TTIsStringWithAnyText(adr.locality)) {
            [addressDictionary setObject:adr.locality forKey:(NSString *)kABPersonAddressCityKey];
        }
        if (TTIsStringWithAnyText(adr.region)) {
            [addressDictionary setObject:adr.region forKey:(NSString *)kABPersonAddressStateKey];
        }
        if (TTIsStringWithAnyText(adr.postalCode)) {
            [addressDictionary setObject:adr.postalCode forKey:(NSString *)kABPersonAddressZIPKey];
        }
        if (TTIsStringWithAnyText(adr.country)) {
            [addressDictionary setObject:adr.country forKey:(NSString *)kABPersonAddressCountryKey];
        }
        if(adr.isHome){
            ABMultiValueAddValueAndLabel(address, addressDictionary, kABHomeLabel, NULL);
        }else if(adr.isWork){
            ABMultiValueAddValueAndLabel(address, addressDictionary, kABWorkLabel, NULL);
        }else 
        {
            ABMultiValueAddValueAndLabel(address, addressDictionary, kABOtherLabel, NULL);
        }
        
        [addressDictionary release];
    }
    ABRecordSetValue(person, kABPersonAddressProperty, address, &anError);
    
    CFRelease(address);    
    
    
    return person;
    
    
    
}

- (void) updateFromPerson:(ABRecordRef) person
{
    if (ABPersonHasImageData(person)){
        self.photo =  (NSData*) ABPersonCopyImageDataWithFormat(person,kABPersonImageFormatThumbnail);
    }else{
        NSXMLElement *elem = [self elementForName:(@"PHOTO")];
        if (elem != nil) {											    
            [self removeChildAtIndex:[[self children] indexOfObject:elem]];	
        }
    }
    self.formattedName = (NSString*)ABRecordCopyCompositeName(person);
    self.givenName = (NSString*)ABRecordCopyValue(person, kABPersonFirstNameProperty);
    self.familyName = (NSString*)ABRecordCopyValue(person, kABPersonLastNameProperty);
    self.middleName = (NSString*)ABRecordCopyValue(person, kABPersonMiddleNameProperty);
    self.prefix = (NSString*)ABRecordCopyValue(person, kABPersonPrefixProperty);
    self.suffix = (NSString*)ABRecordCopyValue(person, kABPersonSuffixProperty);
    self.nickname = (NSString*)ABRecordCopyValue(person, kABPersonNicknameProperty);
    self.orgName = (NSString*)ABRecordCopyValue(person, kABPersonOrganizationProperty);
    self.title = (NSString*)ABRecordCopyValue(person, kABPersonJobTitleProperty);
    self.bday = (NSDate*)ABRecordCopyValue(person, kABPersonBirthdayProperty);
    self.note = (NSString*)ABRecordCopyValue(person, kABPersonNoteProperty);    
    [self clearTelecomsAddresses];
    ABMultiValueRef phones= ABRecordCopyValue(person, kABPersonPhoneProperty); 
    NSString* label;
    NSString* value;
    for(CFIndex i = 0; i < ABMultiValueGetCount(phones); i++) {
        label = (NSString*)ABMultiValueCopyLabelAtIndex(phones , i);
        value = (NSString*)ABMultiValueCopyValueAtIndex(phones , i);
        if(TTIsStringWithAnyText(value)){ 
            NSXMLElement *elem = [NSXMLElement elementWithName:@"TEL"];
            [self addChild:elem];
            
            NSXMLElement *number = [NSXMLElement elementWithName:@"NUMBER"];
            [elem addChild:number];
            [number setStringValue:value];
            
            if([label isEqualToString:(NSString*)kABPersonPhoneMobileLabel]){
                [elem addChild:[NSXMLElement elementWithName:(@"CELL")]];
            }else if([label isEqualToString:(NSString*)kABPersonPhoneMainLabel]){
                [elem addChild:[NSXMLElement elementWithName:(@"PREF")]];                
            }else if([label isEqualToString:(NSString*)kABPersonPhoneHomeFAXLabel]){
                [elem addChild:[NSXMLElement elementWithName:(@"HOME")]];
                [elem addChild:[NSXMLElement elementWithName:(@"FAX")]];
            }else if([label isEqualToString:(NSString*)kABPersonPhoneWorkFAXLabel]){
                [elem addChild:[NSXMLElement elementWithName:(@"WORK")]];
                [elem addChild:[NSXMLElement elementWithName:(@"FAX")]];                
            }else if([label isEqualToString:(NSString*)kABPersonPhoneOtherFAXLabel]){
                [elem addChild:[NSXMLElement elementWithName:(@"FAX")]];                
            }else if([label isEqualToString:(NSString*)kABHomeLabel]){
                [elem addChild:[NSXMLElement elementWithName:(@"HOME")]];
            }else if([label isEqualToString:(NSString*)kABWorkLabel]){
                [elem addChild:[NSXMLElement elementWithName:(@"WORK")]];
            }else if([label isEqualToString:(NSString*)kABPersonPhonePagerLabel]){
                [elem addChild:[NSXMLElement elementWithName:(@"PAGER")]];
            }
        }
    }
    CFRelease(phones);
    [self clearEmailAddresses];
    ABMultiValueRef emails= ABRecordCopyValue(person, kABPersonEmailProperty); 
    
    for(CFIndex i = 0; i < ABMultiValueGetCount(emails); i++) {
        label = (NSString*)ABMultiValueCopyLabelAtIndex(emails , i);
        value = (NSString*)ABMultiValueCopyValueAtIndex(emails , i);
        
        if(TTIsStringWithAnyText(value)){ 
            NSXMLElement *elem = [NSXMLElement elementWithName:@"EMAIL"];
            [self addChild:elem];
            NSXMLElement *userid = [NSXMLElement elementWithName:@"USERID"];
            [elem addChild:userid];
            [userid setStringValue:value];
            
            if([label isEqualToString:(NSString*)kABHomeLabel]){
                [elem addChild:[NSXMLElement elementWithName:(@"HOME")]];
            }else if([label isEqualToString:(NSString*)kABWorkLabel]){
                [elem addChild:[NSXMLElement elementWithName:(@"WORK")]];
                
            }
        }
        
        
    }
    CFRelease(emails);
    
    [self clearAddresses];
    ABMultiValueRef addresses= ABRecordCopyValue(person, kABPersonAddressProperty); 
    
    for(CFIndex i = 0; i < ABMultiValueGetCount(addresses); i++) {
        label = (NSString*)ABMultiValueCopyLabelAtIndex(addresses , i);
        NSDictionary *dict = (NSDictionary *)ABMultiValueCopyValueAtIndex(addresses , i);
        
        
        NSXMLElement *elem = [NSXMLElement elementWithName:@"ADR"];
        [self addChild:elem];
        if([label isEqualToString:(NSString*)kABHomeLabel]){
            [elem addChild:[NSXMLElement elementWithName:(@"HOME")]];
        }else if([label isEqualToString:(NSString*)kABWorkLabel]){
            [elem addChild:[NSXMLElement elementWithName:(@"WORK")]];
            
        }        
        NSXMLElement *street = [NSXMLElement elementWithName:@"STREET"];
        [elem addChild:street];
        [street setStringValue:[dict objectForKey:(NSString *) kABPersonAddressStreetKey]];
        
        NSXMLElement *locality = [NSXMLElement elementWithName:@"LOCALITY"];
        [elem addChild:locality];
        [locality setStringValue:[dict objectForKey:(NSString *) kABPersonAddressCityKey]];        
        
        NSXMLElement *region = [NSXMLElement elementWithName:@"REGION"];
        [elem addChild:region];
        [region setStringValue:[dict objectForKey:(NSString *) kABPersonAddressStateKey]];  
        
        NSXMLElement *postalCode = [NSXMLElement elementWithName:@"PCODE"];
        [elem addChild:postalCode];
        [postalCode setStringValue:[dict objectForKey:(NSString *) kABPersonAddressZIPKey]];          
        
        NSXMLElement *country = [NSXMLElement elementWithName:@"CTRY"];
        [elem addChild:country];
        [country setStringValue:[dict objectForKey:(NSString *) kABPersonAddressCountryKey]];          
    }
    CFRelease(addresses);
}

@end
